package com.ht.module.ai.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ht.abnormal.HtException;
import com.ht.constant.AiChatMessageRoleEnum;
import com.ht.constant.BusConstant;
import com.ht.module.ai.entity.AiChatMessage;
import com.ht.module.ai.entity.AiChatSession;
import com.ht.module.ai.mapper.AiChatMessageMapper;
import com.ht.module.ai.mapper.AiChatSessionMapper;
import com.ht.module.ai.service.AiChatMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ht.util.UserUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * AI聊天历史消息表 服务实现类
 * </p>
 *
 * @author hejialun
 * @since 2025-06-09
 */
@Service
public class AiChatMessageServiceImpl extends ServiceImpl<AiChatMessageMapper, AiChatMessage> implements AiChatMessageService {
    @Resource
    private AiChatSessionMapper chatSessionMapper;

    @Override
    public List<AiChatMessage> findMessageBySessionId(String id) {
        AiChatSession session = chatSessionMapper.selectById(id);
        if(!StrUtil.equals(session.getCreateUser(), UserUtil.getUserId())){
            throw new HtException(BusConstant.NO_PERMISSION);
        }
        return baseMapper.selectList(
                Wrappers.<AiChatMessage>lambdaQuery()
                        .eq(AiChatMessage::getSessionId, id)
                        .in(AiChatMessage::getRole, AiChatMessageRoleEnum.USER,AiChatMessageRoleEnum.AI)
                        .orderByAsc(AiChatMessage::getMessageTime)
        );
    }
}
